﻿@using CnGalWebSite.DrawingBed.Helper.Services;
@using CnGalWebSite.DrawingBed.Models.DataModels;
@inject IFileUploadService _fileUploadService
@inject IPopupService PopupService

<div class="@Class">
    <div class="d-none">
        @if (Multiple)
        {
            <InputFile id="@Id" multiple="multiple" type="file" accept="image/*" OnChange="OnInputFileChange"></InputFile>
        }
        else
        {
            <InputFile id="@Id" type="file" accept="image/*" OnChange="OnInputFileChange"></InputFile>
        }
    </div>

    @if (ShowPreview)
    {
        <div style="display: flex;">
            <MasaImage Src="@ImagePath" Type="ImageType" Style="width: 100%;border-radius: var( --md-card-border-radius);" Alt="预览图" Class="elevation-2" />
            <div class="ps-4 pt-4" style="position: absolute;display: flex;">
                <label for="@Id" class="m-btn m-btn--is-elevated m-btn--has-bg m-size--default theme--dark primary pointer mb-3 me-3 @(Rounded?"m-btn--rounded":"")">
                    <span class="m-btn__content">
                        @if (isUploading)
                        {
                            <MProgressCircular Size="@("20px")" Width="2" Class="me-2" Indeterminate Color="var(--md-sys-color-on-primary)">
                             </MProgressCircular>
                        }
                        else
                        {
                            <i class="@("m-icon m-icon--left theme--dark mdi  "+Icon.ToIconString())">
                            </i>
                        }
                        @Text
                    </span>
                </label>
                @if (string.IsNullOrWhiteSpace(ImagePath) == false)
                {
                    <CnGalWebSite.Components.Buttons.MasaButton OnClick="OnClean" Icon="mdi-trash-can-outline " Class="mb-3" Fab Tooltip="删除" />
                }

            </div>
        </div>
    }
    else
    {
        <label for="@Id" class="m-btn m-btn--is-elevated m-btn--has-bg m-size--default theme--dark primary pointer mb-3 me-3 @(Rounded?"m-btn--rounded":"")">
            <span class="m-btn__content">
                @if (isUploading)
                {
                    <MProgressCircular Size="@("20px")" Width="2" Class="me-2" Indeterminate Color="var(--md-sys-color-on-primary)">
                     </MProgressCircular>
                }
                else
                {
                    <i class="@("m-icon m-icon--left theme--dark mdi  "+Icon.ToIconString())">
                    </i>
                }
                @Text
            </span>
        </label>
    }
</div>


<ImageCropperDialog OnUploadedImage="OnCropperUploaded" @ref="imageCropperViewTip" Gallery="Gallery" />

@code {
    [Parameter]
    public ImageAspectType Type { get; set; }
    [Parameter]
    public ImageType ImageType { get; set; } = ImageType.Horizontal;
    [Parameter]
    public string ImagePath { get; set; }
    [Parameter]
    public EventCallback<string> ImagePathChanged { get; set; }
    [Parameter]
    public EventCallback<string> OnImageUploaded { get; set; }
    [Parameter]
    public bool ShowCropper { get; set; }
    [Parameter]
    public bool ShowPreview { get; set; } = true;
    [Parameter]
    public bool Multiple { get; set; }
    [Parameter]
    public string Text { get; set; } = "上传图片";
    [Parameter]
    public IconType Icon { get; set; } = IconType.Upload;
    [Parameter]
    public string Class { get; set; }
    [Parameter]
    public bool Gallery { get; set; }
    [Parameter]
    public bool Rounded { get; set; } = true;

    private readonly string Id = "input" + new Random().Next();
    bool isUploading;

    ImageCropperDialog imageCropperViewTip;

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    private async Task OnInputFileChange(InputFileChangeEventArgs args)
    {
        isUploading = true;
        StateHasChanged();
        if (Multiple)
        {
            if (args.FileCount > 0)
            {
                foreach (var item in args.GetMultipleFiles())
                {
                    await DirectUpload(item);
                }
            }
        }
        else
        {
            if (imageCropperViewTip != null && ShowCropper)
            {
                imageCropperViewTip.OnInputFileChange(args.File, Type);
            }
            else
            {
                await DirectUpload(args.File);
            }
        }

        isUploading = false;
        StateHasChanged();
    }

    private async Task DirectUpload(IBrowserFile file)
    {
        try
        {
            var obj = await _fileUploadService.UploadImagesAsync(file, Type, Gallery);
            if (obj.Uploaded == true)
            {
                await ChangeImageUrl(obj.Url);
            }
            else
            {
                await PopupService.ToastAsync($"图片上传失败，{obj.Error ?? "网络异常"}", AlertTypes.Error);
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "图片上传失败", "图片大小超过3MB", "将图片压缩后再上传，大图可上传到相册");
        }
    }

    private async Task OnInputFile()
    {
        while (isUploading)
        {
            await Task.Delay(500);
        }
    }

    public async Task OnCropperUploaded(string url)
    {
        await ChangeImageUrl(url);
    }

    public async Task OnClean()
    {
        await ChangeImageUrl(null);
    }

    public async Task ChangeImageUrl(string url)
    {
        ImagePath = url;

        if (string.IsNullOrWhiteSpace(url) == false)
        {
            await OnImageUploaded.InvokeAsync(ImagePath);
        }
        await ImagePathChanged.InvokeAsync(ImagePath);
        StateHasChanged();
    }
}
